package net.atomarrow.sy.base;

import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import net.atomarrow.bean.Pager;
import net.atomarrow.bean.ServiceResult;
import net.atomarrow.controllers.Controller;
import net.atomarrow.render.Render;
import net.atomarrow.sy.bean.TableBean;
import net.atomarrow.sy.bean.User;
import net.atomarrow.sy.form.Form;
import net.atomarrow.sy.staticvariable.KeySv;
import net.atomarrow.util.JsonUtil;
import net.atomarrow.util.StringUtil;

public class BaseController extends Controller {
	
    public  <T extends Form> T getForm(String name,Class<T> clazz){
    	System.out.println(JsonUtil.toJson(getRequest().getParameterMap()));
        T form = getParamObject(name, clazz);
        form.setOrderDir(getParamString("order[0][dir]"));
        form.setOrderColumnNum(getParamInteger("order[0][column]"));
        form.setOrderColumnName(getParamString("columns["+form.getOrderColumnNum()+"][data]"));
        form.setLength(getParamInteger("length"));
        form.setStart(getParamInteger("start"));
        form.setSearchValue(getParamString("search[value]"));
        form.setDraw(getParamInteger("draw"));
        return form;
    }
    public  <T extends Form> T getForm(Class<T> clazz){
       return getForm("form",clazz);
    }

	public Render renderDataTables(List<?> datas,int dataTotal,int draw){
	   return renderJson(JsonUtil.toJson(new TableBean(draw,dataTotal, datas)));
	}
	public Render renderDataTablesWith(List<?> datas,int dataTotal,int draw, String... param) {
	    return renderJson(JsonUtil.toJsonWith(new TableBean(draw,dataTotal, datas),param));
	}
	public Render renderDataTablesWithOut(List<?> datas,int dataTotal,int draw, String... param) {
        return renderJson(JsonUtil.toJsonWithOut(new TableBean(draw,dataTotal, datas),param));
    }
	
    public void setMsg(StringBuilder msg) {
        setMsg(msg.toString());
    }

    public void setMsg(String msg) {
        setAttr("msg", msg);
    }


    /**
     * json操作成功
     * 
     * @
     */
    public Render renderJsonSuccess() {
        return renderJsonSuccess(null);
    }

    /**
     * json操作成功
     * 
     * @
     */
    public Render renderJsonSuccess(String msg) {
        return renderJsonData(new ServiceResult(true, null, msg));
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonData(Object obj) {
        return renderJsonData(obj, null);
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonData(Object obj, Pager pager) {
        if (obj instanceof ServiceResult) {
            ServiceResult serviceResult = (ServiceResult) obj;
            if (pager != null) {
                serviceResult.setPager(pager);
            }
            return renderJsonServiceResult(serviceResult);
        } else {
            return renderJsonServiceResult(new ServiceResult(true, obj, null, pager));
        }
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonServiceResult(ServiceResult result) {
        Object returnResult = result;
        if (result.getResult() != null && result.getResult() instanceof Map) {
            Map map = (Map) result.getResult();
            if (result.getPager() != null) {
                map.put("pager", result.getPager());
            }
            if (result.getMsg() != null) {
                map.put("msg", result.getMsg());
            }
            map.put("success", result.isSuccess());
            returnResult = map;
        }
        if (result.isWithMode()) {
            return renderJson(JsonUtil.toJsonWith(returnResult,
                    result.getWithParams()));
        } else if (result.isWithoutMode()) {
            return renderJson(JsonUtil.toJsonWithOut(returnResult,
                    result.getWithoutParams()));
        }
        return renderJson(JsonUtil.toJson(returnResult));
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonDataWith(Object obj, String... param) {
        if (obj instanceof ServiceResult) {
            return renderJson(JsonUtil.toJsonWith(obj, param));
        }
        return renderJson(JsonUtil.toJsonWith(new ServiceResult(true, obj,
                null), param));
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonDataWith(Object obj, Pager pager, String... param) {
        if (pager != null && param != null) {
            int len = param.length;
            String[] p = new String[len + 6];
            for (int i = 0; i < param.length; i++) {
                p[i] = param[i];
            }
            p[len] = "pager";
            p[len + 1] = "dataTotal";
            p[len + 2] = "pageTotal";
            p[len + 3] = "offset";
            p[len + 4] = "pageSize";
            p[len + 5] = "currentPage";
            param = p;
        }
        return renderJson(JsonUtil.toJsonWith(new ServiceResult(true, obj,
                null, pager), param));
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonDataWithOut(Object obj, String... param) {
        return renderJson(JsonUtil.toJsonWithOut(new ServiceResult(true,
                obj, null), param));
    }

    /**
     * json格式返回
     * 
     * @
     */
    public Render renderJsonDataWithOut(Object obj, Pager pager, String... param) {
        return renderJson(JsonUtil.toJsonWithOut(new ServiceResult(true,
                obj, null, pager), param));
    }


    /**
     * 弹出框中操作成功带刷新
     */
    public Render renderModalSuccess(String msg) {
        if (StringUtil.isNotBlank(msg)) {
            setMsg(msg);
        }
        return renderJsp("/result/success");
    }

    /**
     * 弹出框中操作结果
     */
    public Render renderModalServiceResult(ServiceResult result) {
        if (result.isSuccess()) {
            return renderModalSuccess(result.getMsg());
        } else {
            return renderModalFail(result.getMsg());
        }
    }

    /**
     * 弹出框中操作失败带提示
     */
    public Render renderModalFail(String msg) {
        if (StringUtil.isNotBlank(msg)) {
            setMsg(msg);
        }
        return renderJsp("/result/error");
    }

    /**
     * json操作失败
     * 
     * @param msg
     *            @
     */
    public Render renderJsonFail(String msg) {
        return renderJsonData(new ServiceResult(false, null, msg));
    }

    /**
     * 获取文件后缀名
     * 
     * @param fileName
     * @return
     */
    public String getFileSuffix(String fileName) {
        if (StringUtil.isBlank(fileName)) {
            return "";
        }
        String filesuffix = null;
        StringTokenizer fx = new StringTokenizer(fileName, ".");
        while (fx.hasMoreTokens()) {
            filesuffix = fx.nextToken();
        }
        return filesuffix.toLowerCase();
    }

    /**
     * 获得当前用户的id
     * 
     * @return
     */
    public int getSessionUserId() {
        User user = getSessionUser();
        if (user == null) {
            return 0;
        }
        return user.getId();
    }

    /**
     * 获得当前用户的name
     * 
     * @return
     */
    public String getSessionUserName() {
        User user = getSessionUser();
        if (user == null) {
            return null;
        }
        return user.getName();
    }

    /**
     * 检查分页情况 赋值每页个数
     * 
     * @param pagerCount
     */
    protected Pager checkPager(int pagerCount) {
        Pager pager = getParamObject("pager", Pager.class);
        if (pager == null) {
            pager = new Pager();
        }
        pager.setPageSize(pagerCount);
        return pager;
    }

    public int getSessionRole() {
        if (getSessionUser() == null) {
            return -1;
        }
        return getSessionUser().getRole();
    }

    public User getSessionUser() {
        return (User) getSession().getAttribute(KeySv.SESSION_KEY_USER);
    }
    
    public String getRealPath(String path){
    	return getRequest().getServletContext().getRealPath("/")+path;
    }

}
